/*******************************************************************************
 * Copyright 2013 Mindaugas Idzelis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package incontrol.rcon.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Word {

	private String content;

	public Word(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return getValue();
	}

	public String getValue() {
		return content;
	}

	public void write(OutputStream out) throws IOException {
		byte[] bytes = content.getBytes("ASCII");
		new UInt32(bytes.length).write(out);
		out.write(bytes);
		out.write(0x0);
	}

	public int getSize() {
		return content.length() + 5;
	}

	public static Word read(InputStream in) throws IOException {
		UInt32 length = UInt32.read(in);
		byte[] bytes = new byte[(int) length.getValue()];
		in.read(bytes);
		in.read();
		return new Word(new String(bytes, "ASCII"));
	}
}
